package common.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;

public class ReflectUtil {
	
	public static void setParameter(Field[] fields,Method[] methods,PreparedStatement stmt,Object entity) throws Exception{
		
		for(int i=0;i<fields.length;i++){
			String fieldName = fields[i].getName();

			for (Method method : methods) {
				if(method.getName().contains("get")){
					
					if(method.getName().equalsIgnoreCase("get"+fieldName)){
						
						String ty = fields[i].getType().getName();
//						System.out.println(ty);
						Object invoke = method.invoke(entity);
						if(ty.equals("java.lang.String")){
							stmt.setString(i+1,(String)invoke);
							break;
						} else if(ty.equals("java.lang.Integer")){
							stmt.setInt(i+1,(int)invoke);
							break;
						}
					}
				}
			}
		}
	}
	
	
	
	
	
	/**
	 * 获得要set值的问号？
	 * @param fields
	 * @return
	 */
	public static String getUnkown(Field[] fields){
		
		StringBuffer sb=new StringBuffer();
		sb.append("(");
		for (int i=0;i<fields.length;i++) {
			String name="?"+",";
			
			sb.append(name);
		}
		sb.replace(sb.length()-1, sb.length(),")");
		return sb.toString();
	}
	
	/**
	 * 获得实体的属性
	 * @param fields
	 * @return
	 */
	public static String getEntity(Field[] fields){
		
		StringBuffer sb=new StringBuffer();
		sb.append("(");
		for (int i=0;i<fields.length;i++) {
			String name = fields[i].getName();
			name=name+",";
			sb.append(name);
		}
		sb.replace(sb.length()-1, sb.length(),")");
		return sb.toString().toUpperCase();
	}

}
